using UnityEngine;
using UnityEditor;
using System.Text;
using EntityKit.Runtime;
using System;

namespace EntityKit.Editor
{
    public static class BindBehaviourSubLocation
    {
        public static void CopyBindBehaviourPathToClipboard()
        {
            if (Selection.activeGameObject == null)
            {
                Debug.LogWarning("请先选择一个GameObject");
                return;
            }

            string path = GetBindBehaviourPath(Selection.activeGameObject.transform);
            EditorGUIUtility.systemCopyBuffer = path;
            Debug.Log($"已复制路径到剪贴板: {path}");
        }

        /// <summary>
        /// 获取从根到指定Transform的路径
        /// </summary>
        /// <param name="target">目标Transform</param>
        /// <returns>UI路径</returns>
        private static string GetBindBehaviourPath(Transform target)
        {
            if (target == null) return string.Empty;

            StringBuilder path = new StringBuilder();
            Transform current = target;
            
            while (current != null && !HasBindBehaviour(current))
            {
                if (path.Length > 0)
                    path.Insert(0, "/");
                
                path.Insert(0, current.name);
                current = current.parent;
            }

            return path.ToString();
        }
        
        static bool HasBindBehaviour(Transform transform)
        {
            // 获取所有组件
            Component[] components = transform.GetComponents<Component>();
            
            foreach (Component component in components)
            {
                if (component == null) continue;
                
                if (component is BindBehaviour)
                {
                    return true;
                }
            }
            
            return false;
        }
    }
}